package com.binance.gateway.util;

import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/*
 * 获取url中的顶级域名不包括子域名
 */


public class DomainUtil {
    private static final Logger logger = LoggerFactory.getLogger(DomainUtil.class);
    public static final String domainTails =
            "((\\.com)|(\\.cn)|(\\.org)|(\\.net)|(\\.edu)|(\\.com.cn)|(\\.xyz)|(\\.xin)|(\\.club)|(\\.shop)|(\\.site)|(\\.wang)"
                    + "|(\\.top)|(\\.win)|(\\.online)|(\\.tech)|(\\.store)|(\\.bid)|(\\.cc)|(\\.ren)|(\\.lol)|(\\.pro)|(\\.red)|(\\.kim)|(\\.space)|(\\.link)|(\\.click)|(\\.news)|(\\.news)|(\\.ltd)|(\\.website)"
                    + "|(\\.biz)|(\\.help)|(\\.mom)|(\\.work)|(\\.date)|(\\.loan)|(\\.mobi)|(\\.live)|(\\.studio)|(\\.info)|(\\.pics)|(\\.photo)|(\\.trade)|(\\.vc)|(\\.party)|(\\.game)|(\\.rocks)|(\\.band)"
                    + "|(\\.gift)|(\\.wiki)|(\\.design)|(\\.software)|(\\.social)|(\\.lawyer)|(\\.engineer)|(\\.org)|(\\.net.cn)|(\\.org.cn)|(\\.gov.cn)|(\\.name)|(\\.tv)|(\\.me)|(\\.asia)|(\\.co.ug)|(\\.co)|(\\.press)|(\\.video)|(\\.market)"
                    + "|(\\.games)|(\\.science)|(\\.中国)|(\\.公司)|(\\.网络)|(\\.pub)"
                    + "|(\\.la)|(\\.auction)|(\\.email)|(\\.sex)|(\\.sexy)|(\\.one)|(\\.host)|(\\.rent)|(\\.fans)|(\\.cn.com)|(\\.life)|(\\.cool)|(\\.run)"
                    + "|(\\.gold)|(\\.rip)|(\\.ceo)|(\\.sale)|(\\.hk)|(\\.io)|(\\.gg)|(\\.tm)|(\\.com.hk)|(\\.gs)|(\\.us)|(\\.cloud)|(\\.vision)|(\\.sg)|(\\.eu)|(\\.charity)|(\\.je))";


    private static final Pattern domainPattern = Pattern.compile("[0-9a-zA-Z]+" + domainTails);

    public static String getTopDomain(HttpServletRequest request) {
        StringBuffer url = request.getRequestURL();
        String tempContextUrl =
                url.delete(url.length() - request.getRequestURI().length(), url.length()).append("/").toString();
        try {
            return getTopDomain(tempContextUrl);
        } catch (MalformedURLException e) {
            logger.error("获取TopDomian失败,url={}", url);
        }
        return "";
    }

    public static String getTopDomain(String url) throws MalformedURLException {
        String host = new URL(url).getHost().toLowerCase();// 此处获取值转换为小写
        if (host.contains("localhost")) {
            return "localhost";
        }
        Matcher matcher = domainPattern.matcher(host);
        if (matcher.find()) {
            return matcher.group();
        }
        logger.error("获取TopDomian失败,url={}", url);
        return "";
    }

    public static String getDomain() {
        RequestContext ctx = RequestContext.getCurrentContext();
        StringBuffer url = ctx.getRequest().getRequestURL();
        String tempContextUrl = url.delete(url.length() - ctx.getRequest().getRequestURI().length(), url.length())
                .append("/").toString();
        try {
            String domain = new URL(tempContextUrl).getHost().toLowerCase();
            logger.info("getDomain domain:{}", domain);
            return domain;
        } catch (Exception e) {
            logger.warn("getDomain error:", e);
            return "";
        }

    }
}
